<template>
  <a-drawer
    :width="340"
    :mask-closable="false"
    :visible="dataModel.visible"
    unmount-on-close
    :ok-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel">
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-form
        ref="clientDrawerForm"
        layout="vertical"
        :model="formData"
        :disabled="dataModel.disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="clientId"
          label="客户端id:"
          :disabled="dataModel.type !== Operation.CREATE"
          :rules="[{required: true, message:'请输入客户端id'}]">
          <a-input v-model="formData.clientId" placeholder="请输入客户端id..." allow-clear />
        </a-form-item>
        <a-form-item
          field="clientSecret"
          label="客户端秘钥:"
          :rules="[{required: true, message:'请输入客户端秘钥'}]">
          <a-input v-model="formData.clientSecret" placeholder="请输入客户端秘钥..." allow-clear />
        </a-form-item>
        <a-form-item
          field="scope"
          label="域:">
          <a-input v-model="formData.scope" placeholder="请输入域..." allow-clear />
        </a-form-item>
        <a-form-item field="autoapprove" label="自动放行">
          <a-switch
            v-model:model-value="formData.autoapprove"
            type="round"
            :checked-value="'true'"
            :unchecked-value="'false'"
          >
            <template #checked>
              是
            </template>
            <template #unchecked>
              否
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item
          field="authorizedGrantTypes"
          label="授权模式">
          <a-select v-model="modes" placeholder="请输入授权模式..." allow-create multiple allow-clear>
            <a-option value="password">password</a-option>
            <a-option value="authorization_code">authorization_code</a-option>
            <a-option value="client_credentials">client_credentials</a-option>
            <a-option value="refresh_token">refresh_token</a-option>
            <a-option value="mobile_password">mobile_password</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="accessTokenValidity"
          label="令牌时效:">
          <a-input-number v-model="formData.accessTokenValidity" placeholder="请输入令牌时效..." allow-clear />
        </a-form-item>
        <a-form-item
          field="refreshTokenValidity"
          label="刷新时效:">
          <a-input-number v-model="formData.refreshTokenValidity" placeholder="请输入刷新时效..." allow-clear />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref } from "vue";
import useDataModel from "@/hooks/data-model";
import useLoading from "@/hooks/loading";
import { Operation } from "@/types/global";
import { ExampleClient } from "@/types/modules/auth";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { Message } from "@arco-design/web-vue";
import { create, findById, update } from "@/api/modules/system/client";

const defaultFormData = () => ({
  clientId: undefined,
  clientSecret: undefined,
  resourceIds: undefined,
  scope: undefined,
  authorizedGrantTypes: undefined,
  webServerRedirectUri: undefined,
  authorities: undefined,
  accessTokenValidity: 50,
  refreshTokenValidity: 100,
  autoapprove: 'true'
});

const clientDrawerForm = ref<any>()
const modes = ref<string[] | undefined>([])
const formData = ref<ExampleClient>(defaultFormData());
const { dataModel, openModel, closeModel } = useDataModel();
const { loading, setLoading } = useLoading();
const emit = defineEmits(["refresh"]);

const createHandle = async () => {
  openModel("添加客户端信息", false, true, Operation.CREATE);
}

const updateHandle = async (id: string) => {
  const { data } = await findById(id)
  formData.value  = {
    ...data
  }
  modes.value = data?.authorizedGrantTypes?.split(',')
  openModel('编辑客户端信息', false, true, Operation.UPDATE)
}

const previewHandle = async (id: string) => {
  formData.value = (await findById(id)).data
  openModel('预览客户端信息', true, false, Operation.PREVIEW)
}

const handleCancel = () => {
  closeModel();
  formData.value = defaultFormData()
  setLoading(false)
}
const handleOk = async () => {
  if (dataModel.submit) {
    setLoading(true);
    if (modes?.value) {
      formData.value.authorizedGrantTypes = modes?.value.join(',')
    }
    if (clientDrawerForm.value) {
      clientDrawerForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (dataModel.type === Operation.CREATE) {
            await create(formData.value)
            Message.success({
              content: "添加成功",
              duration: 2000
            });
          } else if (dataModel.type === Operation.UPDATE) {
            await update(formData.value)
            Message.success({
              content: "修改成功",
              duration: 2000
            });
          }
          setLoading(false);
          handleCancel();
          emit("refresh");
        } else {
          setTimeout(() => {
            setLoading(false);
          }, 1000);
        }
      })
    }
  } else {
    handleCancel();
  }
}

defineExpose({ createHandle, updateHandle, previewHandle });
</script>

<script lang="ts">
export default {
  name: "ClientDrawer"
};
</script>

<style scoped>

</style>
